package com.jse;

import java.io.CharArrayWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Io {

	public static String readString(InputStream in) {return readString(in,StandardCharsets.UTF_8);}
	public static String readString(InputStream in,Charset charset) {
		try {
			return new String(in.readAllBytes(),charset);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	public static String readString(Reader reader) {
		try {
			CharArrayWriter w=new CharArrayWriter();
			reader.transferTo(w);
			return w.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	public static byte[] readBytes(InputStream in) {
		try {
			return in.readAllBytes();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	public static void close(AutoCloseable...as) {
		for (AutoCloseable a : as) {
			try {if(a instanceof OutputStream x) {x.flush();}
				a.close();a=null;
			} catch (Exception e) {
				a=null;
			}
		}
	}
	
	public static void read() {
		var file = Path.of("/b.txt");

		try (var channel = AsynchronousFileChannel.open(file)) {
//			file.toFile().length();
		    var buffer = ByteBuffer.allocateDirect(100_000_000);
		    Future<Integer> result = channel.read(buffer, 0);

		    while (!result.isDone()) {
//		        BusinessProcess.doSomethingElse();
		        
		    }

		    var bytesRead = result.get();
		    System.out.println("Bytes read [" + bytesRead + "]");
//		    BusinessProcess.doSomethingWithFile(buffer);
		    buffer.flip();
	        byte[] data = new byte[buffer.limit()];
	        buffer.get(data);
	        System.out.println(new String(data));
	        buffer.clear();
		} catch (IOException | ExecutionException | InterruptedException e) {
		    e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		read();
	}
	
}
